package com.vipboot.framework.web.handler;

import cn.hutool.core.exceptions.ExceptionUtil;

import com.vipboot.framework.core.domain.R;
import com.vipboot.framework.core.exception.ServiceException;
import com.vipboot.framework.core.exception.UserException;
import com.vipboot.framework.core.util.StreamUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.Objects;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R<Void> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                       HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址 {} ,不支持 {} 请求", requestURI, e.getMethod());
        log.error(ExceptionUtil.stacktraceToString(e));
        return R.fail(e.getMessage());
    }


    /**
     * 请求路径中缺少必需的路径变量
     */
    @ExceptionHandler(MissingPathVariableException.class)
    public R<Void> handleMissingPathVariableException(MissingPathVariableException e,
                                                      HttpServletRequest request) {
        String requestURI = request.getRequestURI();
//        log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI);
        log.error("请求地址 {} , 发生 MissingPathVariableException 请求路径中缺少必需的路径变量异常.", requestURI);
        log.error(ExceptionUtil.stacktraceToString(e));
        return R.fail(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
    }

    /**
     * 请求参数类型不匹配
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public R<Void> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址 {} , 发生 MethodArgumentTypeMismatchException 请求参数类型不匹配异常.", requestURI);
        log.error(ExceptionUtil.stacktraceToString(e));
        return R.fail(String.format("请求参数类型不匹配，参数[%s]要求类型为：'%s'，但输入值为：'%s'", e.getName(),
                Objects.requireNonNull(e.getRequiredType()).getName(), e.getValue()));
    }

    /**
     * 处理http请求参数转换异常
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public R<Void> exceptionHandler(HttpMessageNotReadableException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址 {} ,发生 HttpMessageNotReadableException 参数转换异常. {}", requestURI, e.getMessage());
        log.error(ExceptionUtil.stacktraceToString(e));
        return R.fail("参数格式错误");
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public R<Void> handleBindException(BindException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String message = StreamUtil.join(e.getAllErrors(), DefaultMessageSourceResolvable::getDefaultMessage, ", ");
        log.error("请求地址 {} ,发生 BindException 验证异常. {}", requestURI, message);
        log.error(ExceptionUtil.stacktraceToString(e));
        return R.fail(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R<Void> constraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
//        log.error(e.getMessage());
        String requestURI = request.getRequestURI();
        String message = StreamUtil.join(e.getConstraintViolations(), ConstraintViolation::getMessage, ", ");
        log.error("请求地址 {} ,发生 ConstraintViolationException 验证异常. {}", requestURI, message);
        log.error(ExceptionUtil.stacktraceToString(e));
        return R.fail(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
//        log.error(e.getMessage());
        String requestURI = request.getRequestURI();
        log.error("请求地址 {} ,发生 MethodArgumentNotValidException 验证异常. {}", requestURI, e.getMessage());
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        log.error(ExceptionUtil.stacktraceToString(e));
        return R.fail(message);
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public R<Void> handleServiceException(ServiceException e, HttpServletRequest request) {
//        log.error(e.getMessage());
//        String code = String.valueOf(e.getCode());
        Integer code = e.getCode();
        String requestURI = request.getRequestURI();
        log.error("请求地址 {} ,发生业务 ServiceException 异常. {}", requestURI, e.getMessage());
        log.error(ExceptionUtil.stacktraceToString(e));
        return R.fail(code, e.getMessage());
//        return ObjectUtil.isNotNull(code) ? ResponseResult.error(code, e.getMessage())
//                : ResponseResult.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(UserException.class)
    public R<Void> handleUserErrorException(UserException e, HttpServletRequest request) {
        Integer code = e.getCode();
        String requestURI = request.getRequestURI();
        log.error("请求地址 {} ,发生业务 UserErrorException 异常. {}", requestURI, e.getMessage());
        log.error(ExceptionUtil.stacktraceToString(e));
        return R.fail(code, e.getMessage());
//        return ObjectUtil.isNotNull(code) ? ResponseResult.error(code, e.getMessage())
//                : ResponseResult.error(UserErrorCode.USER_ERROR, e.getMessage());
    }


    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public R<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址 {} ,发生 RuntimeException 异常. {}", requestURI, e.getMessage());
//        log.error("请求地址 {} ,发生未知异常.", requestURI, e);
        log.error(ExceptionUtil.stacktraceToString(e));
        return R.fail();
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public R<Void> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
//        log.error("请求地址 {} ,发生系统异常.", requestURI, e);
        log.error("请求地址 {} ,发生 Exception 异常. {}", requestURI, e.getMessage());
        log.error(ExceptionUtil.stacktraceToString(e));
        return R.fail();
    }
}
